<script setup lang="ts">
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {onMounted, ref} from "vue";
import {getUserDetailByIdAPI, modifyUserAPI} from "@/apis/userManage.js";
import {ElMessage, UploadProps} from "element-plus";
import {getAllRoleAPI, getRoleByUserIdAPI} from "@/apis/roleInfo.js";
import {getAllPermissionsAPI, getByUserIdAPI} from "@/apis/permissionInfo.js";
import {updateUserPermissionAPI} from "@/apis/userPermission.js";
import {updateUserRolesAPI} from "@/apis/UserRole.js";


const route = useRoute();
const userInfo=ref({})

const password=ref('');
const passwordConfirm=ref('');

const photoFlag=ref(false);
// 注意，定义一个File类型的ref变量，应该这样子描述
const phototemp=ref<File>();


// 控制提交按钮的可操作性
const disableSwitch=ref(false);


onMounted(async () => {
  if(route.params.id===null||route.params.id===undefined){
    await router.push("/manage/userManager");
  }
  else {
    const res= await getUserDetailByIdAPI(Number(route.params.id));
    userInfo.value=res.data;
  }

  // 这里是角色权限信息自动获取
  const res_role = await getAllRoleAPI();
  res_role.data.forEach((item:{})=>{
    roleInfoList.value.push(role[item.id - 1]);
  })

  const res_permission = await getAllPermissionsAPI();
  res_permission.data.forEach((item:{})=>{
    permissionInfoList.value.push(permission[item.id-1]);
  })

  const res_userRoles=await getRoleByUserIdAPI(route.params.id);
  res_userRoles.data.forEach((item:{})=>{
    roleCheckedList.value.push(role[item.roleId-1]);
  })


  const res_user_permission=await getByUserIdAPI(route.params.id);
  res_user_permission.data.forEach((item:{})=>{
    permissionCheckedList.value.push(permission[item.permissionId-1]);
  })

})

// 以下代码只是演示，后端接口时，新增一个用户，是自动添加了普通用户角色和访问权限的，所以这里就不需要了
enum  role{
  "程序员","超级管理员","管理员","系统管理者","普通用户","访客"
}
enum permission{
  "新增","删除","查询","修改","访问"
}

// 显示角色和权限具体信息列表
const roleInfoList=ref([]);
const permissionInfoList=ref([]);
// 存储角色和权限id列表
const roleIdList=ref([]);
const permissionIdList=ref([]);

const roleCheckedList=ref([]);
const permissionCheckedList=ref([]);
const userRoleData=ref({
  userIds:[],
  roleIds:[],
});
const userPermissionData=ref({
  userIds:[],
  permissionIds:[],
});


// 删除头像的操作
const handleRemove=()=>{
  phototemp.value=undefined;
}

// 用于判断文件大小是否合法，限制重复上传的作用及文件类型
const handleChange: UploadProps['onChange'] = (file,fileList) => {
  //1、判断文件大小是否合法，文件限制不能大于100M===测试暂定是10000，后期改回来
  const fileSizeLimit = (file.size) / 1024 / 1024 < 200;
  if (!fileSizeLimit) {
    ElMessage({
      type: 'error',
      message: '上传文件大小不能超过 200MB!',
    })
    return false;
  }
  else {
    // formData.append('profilePhoto',file.raw);
    photoFlag.value=true;
    phototemp.value=file.raw;
  }
}






// 还是㤇解决这个密码修改的问题，还有这个图片显示的问题
const formData=new FormData();
const modifyOneSummit=async ()=>{
  formData.append('id',userInfo.value.id);
   formData.append('loginName',userInfo.value.loginName);
  formData.append('realName',userInfo.value.realName);
  formData.append('phone',userInfo.value.phone);
  formData.append('email',userInfo.value.email);
  if (phototemp.value!==undefined)
  {
    formData.append('profilePhoto',phototemp.value);
    console.log("图片修改");
  }

  if (password.value===null||passwordConfirm.value===null|| password.value.length===0 || passwordConfirm.value.length===0){
    console.log("1");
    await modifyUserAPI(formData);
    await updateUserRoles();
    await updateUserPermissions();
    await updateUserRolesAPI(userRoleData.value);
    await updateUserPermissionAPI(userPermissionData.value);
    await router.push("/manage/userManager");
  }
  //
else if(password.value.trim()!==passwordConfirm.value.trim()){
    ElMessage({
      type:'error',
      message:'两次密码不一致',
    })
    window.location.reload();
    return;
  }
  else {
    formData.append('password',password.value);
    await modifyUserAPI(formData);
    await updateUserRoles();
    await updateUserPermissions();
    await updateUserRolesAPI(userRoleData.value);
    await updateUserPermissionAPI(userPermissionData.value);
    await router.push("/manage/userManager");
  }

}

const updateUserRoles= async ()=>{
  roleIdList.value=[];
  userRoleData.value={roleIds: [], userIds: []};
  userRoleData.value.userIds.push(route.params.id);
  roleCheckedList.value.forEach((item:string)=>{
    roleIdList.value.push(role[item]+1);
    userRoleData.value.roleIds.push(role[item]+1)
  })
}

const updateUserPermissions=async ()=>{
  permissionIdList.value=[];
  userPermissionData.value={permissionIds: [], userIds: []};
  userPermissionData.value.userIds.push(route.params.id);
  permissionCheckedList.value.forEach((item:string)=>{
    permissionIdList.value.push(permission[item]+1);
    userPermissionData.value.permissionIds.push(permission[item]+1);
  })
}


</script>

<template>
  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/manage/userManager`}" >用户列表</el-breadcrumb-item>
      <el-breadcrumb-item  >修改用户</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="divTable">
    <table class="table">
      <tbody>
      <tr>
        <td class="tableTitle" colspan="4" >用户信息</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF;color: #242424;font-family: 微软雅黑,serif">用户名称</td>
        <td style="width: 350px;height: 15px;   text-align: center  ">{{userInfo.loginName}}</td>
        <td style="width: 250px;height: 15px; text-align: center ;background: #EFF6FF"  >真实姓名</td>
        <td style="width: 350px;height: 15px ; text-align: center"><el-input v-model="userInfo.realName" /></td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">联系电话</td>
        <td style="width: 350px;height: 15px;text-align: center  "><el-input v-model="userInfo.phone"/></td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >电子邮箱</td>
        <td style="width: 350px;height: 15px;text-align: center   "><el-input v-model="userInfo.email"/></td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >密码</td>
        <td style="width: 350px;height: 15px;text-align: center   "><el-input type="password" show-password v-model="password"/></td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >确认密码</td>
        <td style="width: 350px;height: 15px;text-align: center"><el-input  type="password" show-password v-model="passwordConfirm"/></td>
      </tr>

      <!--以下的代码是演示角色和权限的，后续删除      -->
      <tr>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">用户角色列表</td>
        <td colspan="3" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          <el-checkbox-group v-model="roleCheckedList" >
            <!--            后端获取到当前用户的角色列表，并显示-->
            <el-checkbox v-for="(item,index) in roleInfoList" :key="index" :label="item"   >
              {{item}}
            </el-checkbox>
          </el-checkbox-group>
        </td>
      </tr>

      <tr>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">用户权限列表</td>
        <td colspan="3" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          <el-checkbox-group  v-model="permissionCheckedList" >
            <!--            后端获取到当前用户的角色列表，并显示-->
            <el-checkbox v-for="(item,index) in permissionInfoList" :key="index" :label="item"   >
              {{item}}
            </el-checkbox>
          </el-checkbox-group>
        </td>
      </tr>

<!--      <tr>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF"><h3 style="font-family: 'JetBrains Mono',serif;font-weight: bold">用户所在项目</h3></td>
        <td  style="width: 250px;height: 15px;text-align: center;"><h3 style="font-family: 'JetBrains Mono',serif;font-weight: bold">{{locationInfo.projectName}}</h3></td>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF"><h3 style="font-family: 'JetBrains Mono',serif;font-weight: bold">用户所在仓库</h3></td>
        <td  style="width: 250px;height: 15px;text-align: center;"><h3 style="font-family: 'JetBrains Mono',serif;font-weight: bold">{{locationInfo.warehouseName}}</h3></td>
      </tr>-->



      <tr>
        <td colspan="4" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF"></td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">用户头像</td>
        <td  colspan="3" style="width: 350px;height: 15px;text-align: center  ">
          <br>
          <div class="demo-image__preview">
            <el-image
                style="width: 80px; height: 80px"
                :src="userInfo.profilephoto"
                fit="cover"
            >
            </el-image>
          </div>
          <!--          <el-button link type="primary" @click="downPhotos" >打包下载</el-button>-->
          <br>
        </td>
      </tr>
      <tr>
        <td colspan="4" style="background:#EFF6FF ">
          <el-upload
              class="upload-demo"
              ref="upload"
              action=""
              :auto-upload="false"
              :drag="false"
              :on-change="handleChange"
              :on-remove="handleRemove"
              accept=".jpeg,.gif,.jpg,.png,.bmp,"
          >

            <el-button :disabled="photoFlag" type="primary" style="width: 150px;" >请选择需要上传的文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持格式：.jpeg .jpg .png .bmp .gif ，单个文件不能超过200MB
              </div>
            </template>
          </el-upload>
        </td>
      </tr>

      <tr>
        <td colspan="4" style="background:#EFF6FF ">
          <el-button @click="modifyOneSummit" type="primary" :disabled="disableSwitch" style="margin-top: 1%;margin-bottom: 1%" >确认修改</el-button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped lang="scss">

.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}


.divTable {
  position: static;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}



</style>